package tech.kpretty;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Produce {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    // 商品个数
    private int num = 0;

    // 生产
    public void produce() {
        lock.lock();
        try {
            while (num != 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "--> " + (++num));
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    // 消费
    public void consumer() {
        lock.lock();
        try {
            while (num == 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "--> " + (--num));
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

public class ProducerAndConsumer {
    public static void main(String[] args) {
        Produce produce = new Produce();
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                produce.produce();
            }
        }, "生产者").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                produce.consumer();
            }
        }, "消费者").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                produce.produce();
            }
        }, "生产者").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                produce.consumer();
            }
        }, "消费者").start();
    }
}
